package com.cj.peiwan.server.other;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.wei.utils.exception.LogHelper;

import com.cj.peiwan.entity.VerifyCode;
import com.cj.peiwan.server.dao.VerifyCodeDao;
import com.cj.peiwan.server.exception.NotSpecifyIdException;

public class CacheService {
	private static VerifyCodeDao verifyCodeDao = VerifyCodeDao.getInstance();

	public static String getVerifyCode(String username) {
		Map<String, Object> filter = new HashMap<String, Object>();
		filter.put("username", username);
		List<VerifyCode> verifyCodes = verifyCodeDao.findBy(filter, 0, 1);
		if (verifyCodes.isEmpty()) {
			return null;
		} else {
			return verifyCodes.get(0).getVerifyCode();
		}
	}

	public static void setVerifyCode(String username, String verifyCode) {
		Map<String, Object> filter = new HashMap<String, Object>();
		filter.put("username", username);
		List<VerifyCode> verifyCodes = verifyCodeDao.findBy(filter, 0, 2);
		if (verifyCodes.size() > 1) {
			LogHelper.getInstance().error("根据用户名不能查询到多个验证码");
		} else if (verifyCodes.size() == 1) {
			Map<String, Object> oprate = new HashMap<String, Object>();
			oprate.put("verifyCode", verifyCode);
			verifyCodeDao.update(filter, oprate);
		} else {
			VerifyCode code = new VerifyCode();
			code.setId(verifyCodeDao.getNextId());
			code.setUsername(username);
			code.setVerifyCode(verifyCode);
			try {
				verifyCodeDao.insert(code);
			} catch (NotSpecifyIdException e) {
				LogHelper.getInstance().error(e);
			}
		}
	}
}
